<?php

namespace app\controller\wmapi\purchase;

use AlibabaCloud\SDK\Dingtalk\Vworkflow_1_0\Models\PremiumGetFormSchemaResponseBody\result\schemaContent\items\props\push;
use app\controller\wmapi\order\OrderController;
use App\Library\Y;
use app\model\DcdBrands;
use app\model\DcdSeries;
use app\model\DcdSpecsCans;
use app\model\DcdSpecsCansEn;
use app\model\DcdSpecsCansRawData;
use app\model\WaDepartment;
use app\model\WaOrders;
use app\model\WaSalesOrdersExamineApprove;
use app\model\WaSalesOrdersExamineApproveFlow;
use app\model\WpPythonBrands;
use app\model\WpPythonSeries;
use app\model\WpSpecsCans;
use app\model\WaAdmins;
use app\model\WaProducts;
use app\model\WpProductsCans;
use app\controller\wmapi\IndexController;
use app\model\WpUsedSpecsCans;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;
use PDO;
use function MongoDB\BSON\toJSON;
use PDOException;


class DcdProductsController extends Validate
{


    /**
     * 产品品牌列表-不分页
     * @param Request $request
     * @return Response
     */
    public function productListBrands(Request $request)
    {
        $param = $request->all();
        $fields = ['brand_name', 'brand_id'];
        $condition = [];
        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%']; // 产品品牌名称
        }

//        $res = DcdSpecsCans::allBrandByDcdBrand($fields, $condition);
        $res = DcdSpecsCans::allBrandBySpecs($fields, $condition);
        return IndexController::successed($res, '产品品牌不分页列表');

    }


    /**
     * 产品品牌厂商列表-不分页
     * @param Request $request
     * @return Response
     */
    public function productListBrandSub(Request $request)
    {
        $param = $request->all();
        $fields = ['brand_name', 'id', 'sub_brand_name'];
        $condition = [];
        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%']; // 产品品牌名称
        }
        if ($param['sub_brand_name']) {
            $condition [] = ['sub_brand_name', 'like', '%' . $param['sub_brand_name'] . '%']; // 产品品牌厂商名称
        }
        $res = DcdSpecsCans::allBrandSub($fields, $condition);
        return IndexController::successed($res, '产品品牌厂商不分页列表');

    }


    /**
     * 产品品牌车系列表-不分页
     * @param Request $request
     * @return Response
     */
    public function productListSeries(Request $request)
    {
        $param = $request->all();
        $fields = ['brand_name', 'sub_brand_name', 'series_name', 'series_id'];
        $condition = [];

        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%']; // 产品品牌名称
        }
        if ($param['sub_brand_name']) {
            $condition [] = ['sub_brand_name', 'like', '%' . $param['sub_brand_name'] . '%']; // 产品品牌厂商名称
        }
        if ($param['series_name']) {
            $condition [] = ['series_name', 'like', '%' . $param['series_name'] . '%']; // 产品品牌车系名称
        }
        $res = DcdSpecsCans::allSeries($fields, $condition);
        return IndexController::successed($res, '产品品牌车系不分页列表');

    }

    /**
     * 产品品牌车型列表-不分页
     * @param Request $request
     * @return Response
     */
    public function productListModel(Request $request)
    {
        $param = $request->all();
        $fields = [
            'brand_name', 'sub_brand_name', 'series_name', 'car_year', 'car_name', 'car_id',
            'official_price', 'jb', 'length_width_height', 'market_time', 'length',
            'width', 'height', 'seat_count', 'curb_weight', 'full_load_weight',
            'fuel_form', 'is_nev', 'body_struct', 'driver_form', 'car_body_struct',
//            'results_data',
        ];
//        $fields = ['*'];
        $condition = [];

//        if ($param['brand_name']) {
//            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%']; // 产品品牌名称
//        }
//        if ($param['sub_brand_name']) {
//            $condition [] = ['sub_brand_name', 'like', '%' . $param['sub_brand_name'] . '%']; // 产品品牌厂商名称
//        }
//        if ($param['series_name']) {
//            $condition [] = ['series_name', 'like', '%' . $param['series_name'] . '%']; // 产品品牌车系名称
//        }
//        if ($param['car_year']) {
//            $condition [] = ['car_year', 'like', '%' . $param['car_year'] . '%']; // 产品品牌车型年份名称
//        }
//        if ($param['car_name']) {
//            $condition [] = ['car_name', 'like', '%' . $param['car_name'] . '%']; // 产品品牌车型名称
//        }

        if ($param['brand_name']) {
            $condition [] = ['brand_name', '=', $param['brand_name']]; // 产品品牌名称
        }
        if ($param['sub_brand_name']) {
            $condition [] = ['sub_brand_name', '=', $param['sub_brand_name']]; // 产品品牌厂商名称
        }
        if ($param['series_name']) {
            $condition [] = ['series_name', '=', $param['series_name']]; // 产品品牌车系名称
        }
        if ($param['car_year']) {
            $condition [] = ['car_year', '=', $param['car_year']]; // 产品品牌车型年份名称
        }
        if ($param['car_name']) {
            $condition [] = ['car_name', 'like', '%' . $param['car_name'] . '%']; // 产品品牌车型名称
        }


        $res = DcdSpecsCans::all($fields, $condition);
//        $res = DcdSpecsCans::allModel($fields, $condition);
        return IndexController::successed($res, '产品品牌车型不分页列表');

    }


    /**
     * 产品品牌车型年份列表-不分页
     * @param Request $request
     * @return Response
     */
    public function productListModelYear(Request $request)
    {
        $param = $request->all();
        $fields = ['brand_name', 'sub_brand_name', 'series_name', 'car_year'];
        $condition = [];

        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%']; // 产品品牌名称
        }
        if ($param['sub_brand_name']) {
            $condition [] = ['sub_brand_name', 'like', '%' . $param['sub_brand_name'] . '%']; // 产品品牌厂商名称
        }
        if ($param['series_name']) {
            $condition [] = ['series_name', 'like', '%' . $param['series_name'] . '%']; // 产品品牌车系名称
        }
        if ($param['car_year']) {
            $condition [] = ['car_year', 'like', '%' . $param['car_year'] . '%']; // 产品品牌车型年份名称
        }
//        $res = DcdSpecsCans::all($fields, $condition);
        $res = DcdSpecsCans::allModelYear($fields, $condition);
        return IndexController::successed($res, '产品品牌车型不分页列表');

    }


    // 同步dcd车型数据(更新result_data到对应字段)
    public function synSpecsData(Request $request)
    {
        $param = $request->all();
//        19221
        $where = [];
//        $where [] = ['id', '=', 1];
//        $where [] = ['car_id', '=', 5563];
        $where [] = ['id', '>', $param['id1']];
        $where [] = ['id', '<=', $param['id2']];
//        $where [] = ['id', '<', 34000];
        $res = DcdSpecsCans::all(['*'], $where);
        $res = json_decode($res);
//        return IndexController::successed(json_encode($res), '成功');
        $cans = [
            'official_price', 'sub_brand_name', 'jb', 'market_time', 'length_width_height',
            'car_body_struct', 'max_speed', 'acceleration_time', 'length', 'width',
            'width', 'height', 'front_track', 'rear_track', 'body_struct',
            'door_nums', 'door_open_way', 'seat_count', 'curb_weight', 'full_load_weight',
            'driver_form', 'front_suspension_form', 'rear_suspension_form', 'power_steering_type', 'car_body_structure',
            'front_brake_type', 'rear_brake_type', 'park_brake_type', 'front_tire_size', 'rear_tire_size',
            'abs_anti_lock', 'brake_force', 'brake_assist', 'traction_control', 'body_stability_system',
            'active_brake', 'line_support', 'lane_keeping_assist', 'lane_center', 'fatigue_driving_warning',
            'active_dms_fatigue_detection', 'vital_signs_detection', 'road_traffic_sign_recognition', 'signal_recognition', 'night_vision_system',
            'side_air_curtain', 'seat_belt_prompted', 'tire_pressure_system', 'child_seat_interface', 'passive_pedestrian_protection',
            'explosion_tire', 'forward_car_departure_reminder', 'auto_road_change', 'auto_road_out_in', 'auto_park_entry',
            'track_reverse', 'memory_parking', 'auto_park', 'uphill_support', 'steep_slope',
            'air_suspension', 'electromagnetic_induct_suspension', 'variable_steer_system', 'central_differential_lock', 'overall_turn',
            'roof_racks', 'sports_appearance_kit', 'electric_spoiler', 'active_closed_inlet_grid', 'alloy_wheel',
            'frameless_design_door', 'hidden_door_handle', 'drag_hook', 'elec_steer_wheel_adjustment', 'engine_remote_start',
            'remote_control_move', 'car_call', 'header_display_system', 'built_in_tachograph', 'active_noise_reduction',
            'mobile_wireless_charging', 'power_outlet', 'baggage_12v_power_outlet', 'sport_style_seat', 'co_pilot_rear_adjustable_button',
            'rear_cup_holder', 'hot_cold_cup_holder', 'navigation_system', 'position_service', 'bluetooth_and_car_phone',
            'facial_recognition', 'fingerprint_recognition', 'voiceprint_recognition', 'emotion_recognition', 'speech_recognition_system',
            'voice_wake_up_free', 'voice_recognition', 'visible_to_say', 'voice_wake_up_word', 'gesture_control_system',
            'wifi', 'multi_finger_screen_control', 'app_store', 'car_tv', 'rear_lcd_screen',
            'voice_simulate', 'rear_touch_control_system', 'adaptive_light', 'steer_assist_light', 'front_fog_light',
            'headlamp_follow_up', 'headlight_height_adjustment', 'headlight_clean_function', 'headlamp_rain_fog_mode', 'rain_induction_wiper',
            'rear_wiper', 'heated_nozzle', 'rear_independent_air_conditioning', 'rear_exhaust', 'car_purifier',
            'pm25_filtrating_equipment', 'hepa_filter_device', 'negative_ion_generator', 'car_fragrance_device', 'heat_pump_management_system',
            'inner_camera_pixel', 'high_precision_position_system', 'sentinel_mode', 'v2x_communication',
            'car_id', 'car_year', 'car_name', 'dealer_text', 'series_type',
            'series_name', 'series_id', 'product_id', 'product_series_id', 'brand_id',
            'brand_name', 'fuel_form', 'gps', 'ar_reality_navigation',
            'car_networking', 'ota_upgrade', 'results_data',
            "backside_privacy_glass", "driving_computer_display_screen", "car_refrigerator", "incar_camera_count_2",
            "side_footrest", "rear_seat_electric_down", "first_owner_period", "data_network_2",
            "lane_warning_system", "wireless_charging_max_power", "total_electric_power", "wltc_recharge_mileage",
            "electric_layout", "rear_seat_heating", "relax_mode", "gearbox_type", "drive_mode_3", "daytime_light",
            "dow_open_door_warning_system", "rear_electric_window", "vice_drive_leg_adjustment",
            "remote_key_5",
            "layout_seat_4",
            "front_center_airbag", "user_custom_pkg", "cltc_recharge_mileage",
            "electric_drive_number", "drive_mode_6", "battery_energy_density",
            "fast_charge_electricity", "rear_electric_max_power", "center_screen_size",
//            "lcd_dashboard_size_10.25",
            "adaptive_cruise", "total_electric_torque", "car_system_memory_16", "low_headlamp_type",
            "voice_wake_up_recognition_3", "front_electric_window", "ultrasonic_radar", "main_drive_back_and_forth_adjustment",
            "battery_type", "driving_assist_image", "headlamp_delay_off", "rear_usb_typec_interface_count",
            "second_independent_seat", "spare_tire_placement", "main_drive_window_sunshade_mirror", "front_seat_massage",
            "sound_brand", "main_drive_backrest_adjustment", "back_armrest", "vibrate_feedback", "millimeter_wave_radar_3",
            "compression_ratio_s", "vice_drive_backrest_adjustment", "keyless_entry", "max_power_revolution",
            "cylinder_nums", "high_precision_map", "mobile_remote_control_6", "electric_door", "wltc_fuel_comprehensive",
            "multifunction_steer_wheel", "rear_slip_method", "mobile_system_1", "main_drive_seat_adjustment",
            "steer_wheel_material_2", "cruise", "data_network_1", "remote_key_3", "wheelbase", "automatic_drive_level",
            "vice_airbag", "high_headlamp_type", "engine_anti_theft",
//            "lcd_dashboard_size_10.2",
            "engine_max_torque",
            "variable_suspension", "air_control_model", "engine_model", "gearbox_description",
            "air_supply", "reversing_warning_system", "vice_drive_seat_adjustment",
            "mobile_remote_control_5", "multilayer_soundproof_glass",
            "second_row_seat_down_ratio", "engine_max_torque_revolution", "front_armrest", "period", "stalls",
            "window_anti_clip_function", "keyless_start", "cylinder_material",
            "capacity_l", "front_collision_warning", "lcd_dashboard_type", "cylinder_arrangement", "full_speed_adaptive_cruise",
            "energy_elect_max_torque", "spare_tire_specification_2", "auto_headlamp", "window_one_key_lift", "main_airbag",
            "multimedia_interface_1", "main_drive_pillow_adjustment", "front_parking_radar", "central_locking_car",
            "oil_supply", "mobile_system_2", "front_airbag", "mobile_remote_control_8", "electric_back_door_memory",
            "vice_drive_height_adjustment", "vice_drive_waist_adjustment", "front_seat_memory", "front_seat_ventilation",
            "light_special_function", "outside_mirror_memory", "front_seat_heating", "environmental_standards",
            "steer_wheel_adjustment", "oil_tank_volume", "skylight_type", "engine_max_power",
//            "incar_camera_count_1",
            "outside_mirror_electric_folding", "engine_description", "gas_form", "main_drive_height_adjustment", "fuel_label",
            "inside_mirror_auto_anti_glare", "", "", "", "",
            "engine_max_horsepower", "seat_material", "millimeter_wave_radar_1", "rear_parking_radar", "rear_parking_radar",
            "rear_parking_radar", "cylinder_head_material", "main_drive_waist_adjustment", "engine_sas_tech", "camera_count",
            "exter_mirror_elec_adjustment", "front_slip_method", "second_row_small_desktop", "interior_light",
            "engine_unique_tech", "reversing_camera", "car_intelligent_system_MOS智慧车联",
            "vice_drive_back_and_forth_adjustment", "valves_per_cylinder_nums", "electric_back_door", "temperature_partition_control_2",
            "external_mirror_heat", "engine_layout_form", "external_mirror_auto_flip", "baggage_volume",
            "external_mirror_auto_fold", "vice_drive_window_sunshade_mirror", "inductive_back_door", "front_usb_typec_interface_count",
            "mobile_system_5", "speaker", "cylinder_volume_ml", "vice_drive_pillow_adjustment",
            "energy_elect_max_power", "keyless_entry_1", "mobile_system_3", "豪华环境氛围灯_2",
            "light_special_function_像素式", "exter_mirror_auto_prev_glare", "original_etc", "fuel_comprehensive", "seat_material_2",
            "rear_airbag", "main_drive_leg_adjustment", "seat_material_1", "智享套装_2", "steer_wheel_material_3",
            "steer_wheel_shift", "智享套装_1", "electric_max_power", "智联套装_1", "panoramic_camera",
            "voice_wake_up_recognition_2", "智驾套装_2", "millimeter_wave_radar", "temperature_partition_control_1",
            "car_intelligent_system_MBUX", "temperature_partition_control_3", "drive_mode_2", "electric_max_torque", "智联套装_2",
            "voice_wake_up_recognition_1", "drive_mode_1", "engine_max_power_horsepower", "front_electric_max_horsepower",
            "vtol_power_station", "quick_charge_position", "lcd_dashboard_size_7", "battery_warranty",
            'outer_camera_pixel', 'lane_keeping_a', 'match_value', "main_vice_knee_airbag", "window_sunshade",
            "front_windshield_electric_heating", "active_ambient_light", "light_sensing_canopy",
            "second_seat_control_functional", "front_near_center_airbag", "voice_wake_up_recognition",
            "drive_mode", "usb_typec_interface_max_charging_power", "rear_seat_functional", "second_local_seat",
            "spare_tire_specification", "豪华环境氛围灯_1", "front_seat_functional", "battery_charge",
            'main_knee_airbag', '智驾套装_1', 'power_consumption'
        ];


        foreach ($res as $k) {


            $data = [];
            $ty = gettype($k->results_data);
            if ($ty == 'string') {
                $k->results_data = json_decode($k->results_data);
            }
            $data['updated_at'] = dateTime();
            foreach ($k->results_data as $ke) {
                if ($ke->key == 'engine_max_torque') {
                }
                if (in_array($ke->key, $cans)) {
                    if ($ke->key != 'results_data') {
                        $data[$ke->key] = $ke->value;

                    }
                }
            }
            $condition = [];
            $condition [] = ['id', '=', $k->id];
            $up = DcdSpecsCans::updated($condition, $data);
            if (!$up) {
                return IndexController::errored('', '失败');
            }

        }
        return IndexController::successed(1, '成功');

    }

    // 同步dcd车型数据(更新result_data_all到对应字段 暂时无用)
    public function synSpecsDataAll(Request $request)
    {
//        19221
        $where = [];
        $where [] = ['id', '=', 1];
//        $where [] = ['car_id', '=', 5563];
//        $where [] = ['id', '>', 20000];
//        $where [] = ['id', '<', 20001];
//        $where [] = ['id', '<', 34000];
        $res = DcdSpecsCansRawData::all(['*'], $where);
        if ($res) {
            $res = json_decode($res);

            $cans = [
                'official_price', 'sub_brand_name', 'jb', 'market_time', 'length_width_height',
                'car_body_struct', 'max_speed', 'acceleration_time', 'length', 'width',
                'width', 'height', 'front_track', 'rear_track', 'body_struct',
                'door_nums', 'door_open_way', 'seat_count', 'curb_weight', 'full_load_weight',
                'driver_form', 'front_suspension_form', 'rear_suspension_form', 'power_steering_type', 'car_body_structure',
                'front_brake_type', 'rear_brake_type', 'park_brake_type', 'front_tire_size', 'rear_tire_size',
                'abs_anti_lock', 'brake_force', 'brake_assist', 'traction_control', 'body_stability_system',
                'active_brake', 'line_support', 'lane_keeping_assist', 'lane_center', 'fatigue_driving_warning',
                'active_dms_fatigue_detection', 'vital_signs_detection', 'road_traffic_sign_recognition', 'signal_recognition', 'night_vision_system',
                'side_air_curtain', 'seat_belt_prompted', 'tire_pressure_system', 'child_seat_interface', 'passive_pedestrian_protection',
                'explosion_tire', 'forward_car_departure_reminder', 'auto_road_change', 'auto_road_out_in', 'auto_park_entry',
                'track_reverse', 'memory_parking', 'auto_park', 'uphill_support', 'steep_slope',
                'air_suspension', 'electromagnetic_induct_suspension', 'variable_steer_system', 'central_differential_lock', 'overall_turn',
                'roof_racks', 'sports_appearance_kit', 'electric_spoiler', 'active_closed_inlet_grid', 'alloy_wheel',
                'frameless_design_door', 'hidden_door_handle', 'drag_hook', 'elec_steer_wheel_adjustment', 'engine_remote_start',
                'remote_control_move', 'car_call', 'header_display_system', 'built_in_tachograph', 'active_noise_reduction',
                'mobile_wireless_charging', 'power_outlet', 'baggage_12v_power_outlet', 'sport_style_seat', 'co_pilot_rear_adjustable_button',
                'rear_cup_holder', 'hot_cold_cup_holder', 'navigation_system', 'position_service', 'bluetooth_and_car_phone',
                'facial_recognition', 'fingerprint_recognition', 'voiceprint_recognition', 'emotion_recognition', 'speech_recognition_system',
                'voice_wake_up_free', 'voice_recognition', 'visible_to_say', 'voice_wake_up_word', 'gesture_control_system',
                'wifi', 'multi_finger_screen_control', 'app_store', 'car_tv', 'rear_lcd_screen',
                'voice_simulate', 'rear_touch_control_system', 'adaptive_light', 'steer_assist_light', 'front_fog_light',
                'headlamp_follow_up', 'headlight_height_adjustment', 'headlight_clean_function', 'headlamp_rain_fog_mode', 'rain_induction_wiper',
                'rear_wiper', 'heated_nozzle', 'rear_independent_air_conditioning', 'rear_exhaust', 'car_purifier',
                'pm25_filtrating_equipment', 'hepa_filter_device', 'negative_ion_generator', 'car_fragrance_device', 'heat_pump_management_system',
                'inner_camera_pixel', 'high_precision_position_system', 'sentinel_mode', 'v2x_communication',
                'car_id', 'car_year', 'car_name', 'dealer_text', 'series_type',
                'series_name', 'series_id', 'product_id', 'product_series_id', 'brand_id',
                'brand_name', 'fuel_form', 'gps', 'ar_reality_navigation',
                'car_networking', 'ota_upgrade', 'results_data',
                "backside_privacy_glass", "driving_computer_display_screen", "car_refrigerator", "incar_camera_count_2",
                "side_footrest", "rear_seat_electric_down", "first_owner_period", "data_network_2",
                "lane_warning_system", "wireless_charging_max_power", "total_electric_power", "wltc_recharge_mileage",
                "electric_layout", "rear_seat_heating", "relax_mode", "gearbox_type", "drive_mode_3", "daytime_light",
                "dow_open_door_warning_system", "rear_electric_window", "vice_drive_leg_adjustment",
                "remote_key_5",
//                "layout_seat_4",
                "front_center_airbag", "user_custom_pkg", "cltc_recharge_mileage",
                "electric_drive_number", "drive_mode_6", "battery_energy_density",
                "fast_charge_electricity", "rear_electric_max_power", "center_screen_size",
//            "lcd_dashboard_size_10.25",
                "adaptive_cruise", "total_electric_torque", "car_system_memory_16", "low_headlamp_type",
                "voice_wake_up_recognition_3", "front_electric_window", "ultrasonic_radar", "main_drive_back_and_forth_adjustment",
                "battery_type", "driving_assist_image", "headlamp_delay_off", "rear_usb_typec_interface_count",
                "second_independent_seat", "spare_tire_placement", "main_drive_window_sunshade_mirror", "front_seat_massage",
                "sound_brand", "main_drive_backrest_adjustment", "back_armrest", "vibrate_feedback", "millimeter_wave_radar_3",
                "compression_ratio_s", "vice_drive_backrest_adjustment", "keyless_entry", "max_power_revolution",
                "cylinder_nums", "high_precision_map", "mobile_remote_control_6", "electric_door", "wltc_fuel_comprehensive",
                "multifunction_steer_wheel", "rear_slip_method", "mobile_system_1", "main_drive_seat_adjustment",
                "steer_wheel_material_2", "cruise", "data_network_1", "remote_key_3", "wheelbase", "automatic_drive_level",
                "vice_airbag", "high_headlamp_type", "engine_anti_theft",
//            "lcd_dashboard_size_10.2",
                "engine_max_torque",
                "variable_suspension", "air_control_model", "engine_model", "gearbox_description",
                "air_supply", "reversing_warning_system", "vice_drive_seat_adjustment",
                "mobile_remote_control_5", "multilayer_soundproof_glass",
                "second_row_seat_down_ratio", "engine_max_torque_revolution", "front_armrest", "period", "stalls",
                "window_anti_clip_function", "keyless_start", "cylinder_material",
                "capacity_l", "front_collision_warning", "lcd_dashboard_type", "cylinder_arrangement", "full_speed_adaptive_cruise",
                "energy_elect_max_torque", "spare_tire_specification_2", "auto_headlamp", "window_one_key_lift", "main_airbag",
                "multimedia_interface_1", "main_drive_pillow_adjustment", "front_parking_radar", "central_locking_car",
                "oil_supply", "mobile_system_2", "front_airbag", "mobile_remote_control_8", "electric_back_door_memory",
                "vice_drive_height_adjustment", "vice_drive_waist_adjustment", "front_seat_memory", "front_seat_ventilation",
                "light_special_function", "outside_mirror_memory", "front_seat_heating", "environmental_standards",
                "steer_wheel_adjustment", "oil_tank_volume", "skylight_type", "engine_max_power",
//            "incar_camera_count_1",
                "outside_mirror_electric_folding", "engine_description", "gas_form", "main_drive_height_adjustment", "fuel_label",
                "inside_mirror_auto_anti_glare", "", "", "", "",
                "engine_max_horsepower", "seat_material", "millimeter_wave_radar_1", "rear_parking_radar", "rear_parking_radar",
                "rear_parking_radar", "cylinder_head_material", "main_drive_waist_adjustment", "engine_sas_tech", "camera_count",
                "exter_mirror_elec_adjustment", "front_slip_method", "second_row_small_desktop", "interior_light",
                "engine_unique_tech", "reversing_camera", "car_intelligent_system_MOS智慧车联",
                "vice_drive_back_and_forth_adjustment", "valves_per_cylinder_nums", "electric_back_door", "temperature_partition_control_2",
                "external_mirror_heat", "engine_layout_form", "external_mirror_auto_flip", "baggage_volume",
                "external_mirror_auto_fold", "vice_drive_window_sunshade_mirror", "inductive_back_door", "front_usb_typec_interface_count",
                "mobile_system_5", "speaker", "cylinder_volume_ml", "vice_drive_pillow_adjustment",
                "energy_elect_max_power", "keyless_entry_1", "mobile_system_3", "豪华环境氛围灯_2",
                "light_special_function_像素式", "exter_mirror_auto_prev_glare", "original_etc", "fuel_comprehensive", "seat_material_2",
                "rear_airbag", "main_drive_leg_adjustment", "seat_material_1", "智享套装_2", "steer_wheel_material_3",
                "steer_wheel_shift", "智享套装_1", "electric_max_power", "智联套装_1", "panoramic_camera",
                "voice_wake_up_recognition_2", "智驾套装_2", "millimeter_wave_radar", "temperature_partition_control_1",
                "car_intelligent_system_MBUX", "temperature_partition_control_3", "drive_mode_2", "electric_max_torque", "智联套装_2",
                "voice_wake_up_recognition_1", "drive_mode_1", "engine_max_power_horsepower", "front_electric_max_horsepower",
                "vtol_power_station", "quick_charge_position", "lcd_dashboard_size_7", "battery_warranty",
                'outer_camera_pixel', 'lane_keeping_a', 'match_value', "main_vice_knee_airbag", "window_sunshade",
                "front_windshield_electric_heating", "active_ambient_light", "light_sensing_canopy",
                "second_seat_control_functional", "front_near_center_airbag", "voice_wake_up_recognition",
                "drive_mode", "usb_typec_interface_max_charging_power", "rear_seat_functional", "second_local_seat",
                "spare_tire_specification", "豪华环境氛围灯_1", "front_seat_functional", "battery_charge",
                'main_knee_airbag', '智驾套装_1', 'power_consumption'
            ];


            foreach ($res as $k) {


                $data = [];
                $ty = gettype($k->results_data_all);
//                if ($ty == 'string') {
                $k->results_data_all = json_decode($k->results_data_all);
//                }

                $data['updated_at'] = dateTime();
                foreach ($k->results_data_all as $ke) {
                    if (in_array($ke->key, $cans)) {
                        if ($ke->key != 'results_data_all') {
                            $data[$ke->key] = $ke->text;

                        }
                    }
                }
                $condition = [];
                $condition [] = ['id', '=', $k->id];
                $up = DcdSpecsCansRawData::updated($condition, $data);
                if (!$up) {
                    return IndexController::errored('', '失败');
                }

            }


        }
//        return IndexController::successed(json_encode($res), '成功');

        return IndexController::successed(1, '成功');

    }


    // 同步dcd车型数据( 解析 result_data )
    public function synResultData(Request $request)
    {
//        19221
        $where = [];
        $whereIn = [100195, 97955, 97126, 87128, 77251, 93540, 76433, 29570, 241330, 101199, 97402, 94418, 94765];
//        $where [] = ['id', '<', 3];
        $res = DcdSpecsCans::allWhereIn(['*'], $where, $whereIn);
        $res = json_decode($res);
        foreach ($res as $k) {

            $data = [];
            $data_can = [];
            $ty = gettype($k->results_data);
            if ($ty == 'string') {
                $k->results_data = json_decode($k->results_data);
            }
            $data['updated_at'] = dateTime();
//            foreach ($k->results_data as $ke) {
//                    if ($ke->key != 'results_data') {
//                        $data_can[$ke->key] = str($ke->value);
//                    }
//            }
            $condition = [];
            $condition [] = ['car_id', '=', $k->car_id];
            $data['results_data_syn'] = serialize($k->results_data);
            $up = DcdSpecsCans::updated($condition, $data);
            if (!$up) {
                return IndexController::errored('', '失败');
            }

        }
        return IndexController::successed(1, '成功');
    }


    // 同步dcd车型数据补漏更新(更新result_data到对应字段)
    public function synSpecsDataBuLou(Request $request)
    {
        $where = [];
        $where [] = ['official_price', '=', 0];
        $res = DcdSpecsCans::all(['*'], $where);
        $res = json_decode($res);
        $cans = [
            'official_price', 'sub_brand_name', 'jb', 'market_time', 'length_width_height',
            'car_body_struct', 'max_speed', 'acceleration_time', 'length', 'width',
            'width', 'height', 'front_track', 'rear_track', 'body_struct',
            'door_nums', 'door_open_way', 'seat_count', 'curb_weight', 'full_load_weight',
            'driver_form', 'front_suspension_form', 'rear_suspension_form', 'power_steering_type', 'car_body_structure',
            'front_brake_type', 'rear_brake_type', 'park_brake_type', 'front_tire_size', 'rear_tire_size',
            'abs_anti_lock', 'brake_force', 'brake_assist', 'traction_control', 'body_stability_system',
            'active_brake', 'line_support', 'lane_keeping_assist', 'lane_center', 'fatigue_driving_warning',
            'active_dms_fatigue_detection', 'vital_signs_detection', 'road_traffic_sign_recognition', 'signal_recognition', 'night_vision_system',
            'side_air_curtain', 'seat_belt_prompted', 'tire_pressure_system', 'child_seat_interface', 'passive_pedestrian_protection',
            'explosion_tire', 'forward_car_departure_reminder', 'auto_road_change', 'auto_road_out_in', 'auto_park_entry',
            'track_reverse', 'memory_parking', 'auto_park', 'uphill_support', 'steep_slope',
            'air_suspension', 'electromagnetic_induct_suspension', 'variable_steer_system', 'central_differential_lock', 'overall_turn',
            'roof_racks', 'sports_appearance_kit', 'electric_spoiler', 'active_closed_inlet_grid', 'alloy_wheel',
            'frameless_design_door', 'hidden_door_handle', 'drag_hook', 'elec_steer_wheel_adjustment', 'engine_remote_start',
            'remote_control_move', 'car_call', 'header_display_system', 'built_in_tachograph', 'active_noise_reduction',
            'mobile_wireless_charging', 'power_outlet', 'baggage_12v_power_outlet', 'sport_style_seat', 'co_pilot_rear_adjustable_button',
            'rear_cup_holder', 'hot_cold_cup_holder', 'navigation_system', 'position_service', 'bluetooth_and_car_phone',
            'facial_recognition', 'fingerprint_recognition', 'voiceprint_recognition', 'emotion_recognition', 'speech_recognition_system',
            'voice_wake_up_free', 'voice_recognition', 'visible_to_say', 'voice_wake_up_word', 'gesture_control_system',
            'wifi', 'multi_finger_screen_control', 'app_store', 'car_tv', 'rear_lcd_screen',
            'voice_simulate', 'rear_touch_control_system', 'adaptive_light', 'steer_assist_light', 'front_fog_light',
            'headlamp_follow_up', 'headlight_height_adjustment', 'headlight_clean_function', 'headlamp_rain_fog_mode', 'rain_induction_wiper',
            'rear_wiper', 'heated_nozzle', 'rear_independent_air_conditioning', 'rear_exhaust', 'car_purifier',
            'pm25_filtrating_equipment', 'hepa_filter_device', 'negative_ion_generator', 'car_fragrance_device', 'heat_pump_management_system',
            'outer_camera_pixel', 'inner_camera_pixel', 'high_precision_position_system', 'sentinel_mode', 'v2x_communication',
            'car_id', 'car_year', 'car_name', 'dealer_text', 'series_type',
            'series_name', 'series_id', 'product_id', 'product_series_id', 'brand_id',
            'brand_name', 'lane_keeping_a', 'fuel_form', 'gps', 'ar_reality_navigation',
            'car_networking', 'ota_upgrade', 'match_value', 'results_data',
        ];
        foreach ($res as $k) {

            $data = [];
            $ty = gettype($k->results_data);
            if ($ty == 'string') {
                $k->results_data = json_decode($k->results_data);
            }
            $data['updated_at'] = dateTime();
            foreach ($k->results_data as $ke) {
                if (in_array($ke->key, $cans)) {
                    if ($ke->key != 'results_data') {
                        $data[$ke->key] = $ke->value;

                    }
                }
            }
            $condition = [];
            $condition [] = ['id', '=', $k->id];
            $up = DcdSpecsCans::updated($condition, $data);
            if (!$up) {
                return IndexController::errored('', '失败');
            }

        }
        return IndexController::successed(1, '成功');
    }


    /**
     * 同步车系数据到车型信息
     * @param Request $request
     */
    public function synSubidSpecsData(Request $request)
    {
        $dcd_series = DcdSeries::all(['*'], []);
        $dcd_series = json_decode($dcd_series);
        $i = 0;
        foreach ($dcd_series as $k) {
            $data = ['sub_brand_id' => $k->sub_brand_id, 'sub_brand_name' => $k->sub_brand_name, 'updated_at' => dateTime()];
            $where = [];
            $where [] = ['series_id', '=', $k->series_id];
            if ($k->sub_brand_name) {
                $find = DcdSpecsCans::find($where);
                $find = json_decode($find);
                if ($find) {
                    $up = DcdSpecsCans::updated($where, $data);
                    if ($up) {
                        $i = $i + 1;
                    }
                }
            }
        }

        return IndexController::successed($i, '成功');
    }


    /**
     * 同步品牌首字母数据到车型信息
     * @param Request $request
     */
    public function synSubBrandFirstLetterData(Request $request)
    {
        $param = $request->all();
        $condition = [];
        $condition [] = ['pinyin', '=', $param['pinyin']];
        $whereIn = $param['where_in'];

        if ($whereIn) {
            $dcd_brands = DcdBrands::allIn(['*'], $whereIn);
            $dcd_brands = json_decode($dcd_brands);
        } else {
            $dcd_brands = DcdBrands::all(['*'], $condition);
            $dcd_brands = json_decode($dcd_brands);
        }

        $i = 0;
        foreach ($dcd_brands as $k) {
            $data = ['first_letter' => $k->pinyin, 'updated_at' => dateTime()];
            $where = [];
            $where [] = ['brand_id', '=', $k->brand_id];
            if ($k->pinyin) {
                $find = DcdSpecsCans::find($where);
                $find = json_decode($find);
                if ($find) {
                    $up = DcdSpecsCans::updated($where, $data);
                    if ($up) {
                        $i = $i + 1;
                    }
                }
            }
        }

        return IndexController::successed($i, '成功');
    }

    /**
     * 同步dcd车型数据(归类新能源传统能源)
     * @param Request $request
     * @return Response
     */
    public function classifySpecsNev(Request $request)
    {
        $param = $request->all();
        $where = [];
        $where [] = ['id', '>', $param['id1']];
        $where [] = ['id', '<=', $param['id2']];
        $dcd_specs_cans = DcdSpecsCans::all(['*'], $where);
        $dcd_specs_cans = json_decode($dcd_specs_cans);
        foreach ($dcd_specs_cans as $k) {
            // 是否新能源 1 是 新能源  2 是 传统能源
            if ($k->fuel_form) {
                if ($k->fuel_form == '柴油') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '柴油';
                } elseif ($k->fuel_form == '汽油') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '汽油';
                } elseif ($k->fuel_form == '油电混合') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '油电混合';
                } elseif ($k->fuel_form == '柴油') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '柴油';
                } elseif ($k->fuel_form == '48V轻混系统') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '48V轻混系统';
                } elseif ($k->fuel_form == '插电式混合动力') {
                    $k->is_nev = '1';
                    $k->is_nev_name = '插电式混合动力';
                } elseif ($k->fuel_form == '压缩天然气(CNG)') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '压缩天然气(CNG)';
                } elseif ($k->fuel_form == '增程式') {
                    $k->is_nev = '1';
                    $k->is_nev_name = '增程式';
                } elseif ($k->fuel_form == '汽油电驱') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '汽油电驱';
                } elseif ($k->fuel_form == '氢燃料电池') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '氢燃料电池';
                } elseif ($k->fuel_form == '醇电混合') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '醇电混合';
                } elseif ($k->fuel_form == '未知') {
                    $k->is_nev = '2';
                    $k->is_nev_name = '未知';
                } elseif ($k->fuel_form == '纯电动') {
                    $k->is_nev = '1';
                    $k->is_nev_name = '纯电动';
                } else {
                    $k->is_nev = '2';
                    $k->is_nev_name = '汽油';
                }
                $data = ['is_nev' => $k->is_nev, 'updated_at' => dateTime()];
                $where = ['car_id' => $k->car_id];

                $up = DcdSpecsCans::updated($where, $data);
                if (!$up) {
                    echo 2222222222222;
                }

            }

        }
        return IndexController::successed('', '成功');
    }


    /**
     * 保留的品牌清单
     * @param Request $request
     */
    public function reserveBrands(Request $request)
    {
        $whereNotIn = [
            'AITO', 'ARCFOX极狐', 'iCAR', 'Jeep', 'MINI',
            'Polestar极星', 'SERES赛力斯', 'smart', 'SRM鑫源', 'SWM斯威汽车',
            '上汽大通MAXUS', '东风', '东风奕派', '东风富康', '东风小康',
            '东风纳米', '东风风光', '东风风度', '东风风神', '东风风行',
            '中国重汽', '中国重汽VGV', '丰田', '乐道', '云度',
            '五菱汽车', '享界', '仰望', '依维柯', '保时捷',
            '凯翼', '凯迪拉克', '别克', '北京', '北汽制造',
            '合创汽车', '吉利几何', '吉利汽车', '吉利银河',
            '名爵', '启辰', '哈弗', '哪吒汽车', '坦克',
            '埃安', '大众', '奇瑞', '奇瑞新能源', '奔腾',
            '奔驰', '奥迪', '宇通客车', '安凯客车', '宏远汽车',
            '宝马', '宝骏', '小米汽车', '小鹏汽车', '岚图',
            '广汽传祺', '开沃汽车', '开瑞', '思皓', '捷尼赛思',
            '捷豹', '捷达', '捷途', '摩登汽车', '斯柯达',
            '方程豹', '日产', '昊铂', '星途', '星驰',
            '智己汽车', '智界', '曹操汽车', '本田', '极氪',
            '极石汽车', '极越', '林肯', '标致', '理想汽车',
            '欧拉', '比亚迪', '江汽集团', '江淮汽车', '江淮瑞风',
            '江淮钇为', '江铃', '江铃晶马汽车', '江铃集团新能源', '沃尔沃',
            '深蓝汽车', '特斯拉', '猛士', '现代', '理念',
            '瑞驰', '睿蓝汽车', '福特', '福田', '科尼赛克',
            '腾势', '荣威', '蓝电', '蔚来', '起亚',
            '路虎', '远程汽车', '道奇', '金旅', '金杯新能源',
            '金龙', '长城', '长安', '长安凯程', '长安启源',
            '红旗', '长安欧尚', '路特斯', '长安跨越', '阿维塔',
            '雪佛兰', '雪铁龙', '零跑汽车', '雷克萨斯', '领克',
            '飞凡汽车', '高合', '魏牌',
        ];
        $data_up = [
            'reserve_brands' => 2, // 是否是保留的品牌 1是 2不是
            'updated_at' => dateTime(),
        ];

        $res = DcdSpecsCans::updatedReserveBbrands($whereNotIn, $data_up);
        $res = json_decode($res);
        return IndexController::successed($res, '成功');
    }


    /**
     * 解析result_data数据 根据 fuel_form 新增缺失字段
     * @param $table
     * @param $column
     * @param $type
     */
    public function checkAndAddColumn()
    {
        $table = 'dcd_specs_cans';
        $type = 'VARCHAR(50)';
        $where = [];
//        $where [] = ['id', '=', 1];
        $whereIn = [100195, 97955, 97126, 87128, 77251, 93540, 76433, 29570, 241330, 101199, 97402, 94418, 94765];
//        $where [] = ['id', '<', 34000];
        $res = DcdSpecsCans::allWhereIn(['*'], $where, $whereIn);
        $res = json_decode($res);
        foreach ($res as $k) {

            $data = [];
            $ty = gettype($k->results_data);
            if ($ty == 'string') {
                $k->results_data = json_decode($k->results_data);
            }
            $data['updated_at'] = dateTime();
            foreach ($k->results_data as $ke) {
                $column = $ke->key;


// 使用示例
                $table = 'dcd_specs_cans';
                $tableName = 'dcd_specs_cans';
                $fields = [$ke->key];
                $fieldName = $ke->key;

                $dsn = 'mysql:host=localhost;dbname=webman;charset=utf8mb4';
                $username = 'root';
                $password = 123456;
                $pdo = new PDO($dsn, $username, $password);


// 构建查询字段是否存在的SQL语句
                $sql = "SHOW COLUMNS FROM `$tableName` LIKE '$fieldName'";

// 执行查询
                $stmt = $pdo->query($sql);

// 检查是否有结果返回
                if ($stmt->rowCount() === 0) {
                    // 字段不存在，添加新字段
                    // 注意：这里需要根据你使用的数据库（如MySQL、PostgreSQL等）编写正确的ALTER TABLE语句
                    $alterTableSql = "ALTER TABLE `$tableName` ADD `$fieldName` VARCHAR(10)";
                    $pdo->exec($alterTableSql);
                }

// 关闭查询语句
                $stmt->closeCursor();


//                if (fieldsExist($table, $fields)) {
//                    echo "字段存在。";
//                } else {
//                Db::table($column, function ($table) use ($column) {
//                    $table->addColumn('varchar', $column, ['length' => 50]); // 示例为varchar类型，长度255
//                });
//                }


            }

        }


        return IndexController::successed('', '成功');


    }


    /**
     * 补充raw_data缺失字段
     * @return Response
     */
    public function checkRawDataAddColumn()
    {
        $table = 'dcd_specs_cans';
        $type = 'VARCHAR(50)';
        $where = [];
        $where [] = ['id', '=', 1];
        $whereIn = [];
//        $whereIn = [751, 34, 1882, 42272, 116, 6174, 246, 9, 97, 4887, 31845, 9176, 644];
//        $where [] = ['id', '<', 34000];
        $res = DcdSpecsCansRawData::allWhereIn(['*'], $where, $whereIn);
        $res = json_decode($res);
        foreach ($res as $k) {

            $data = [];
            $ty = gettype($k->results_data_all);
            if ($ty == 'string') {
                $k->results_data_all = json_decode($k->results_data_all);
            }
            $data['updated_at'] = dateTime();
            foreach ($k->results_data_all as $ke) {
                $column = $ke->key;


// 使用示例
                $table = 'dcd_specs_cans_raw_data';
                $tableName = 'dcd_specs_cans_raw_data';
                $fields = [$ke->key];
                $fieldName = $ke->key;

                $dsn = 'mysql:host=localhost;dbname=webman;charset=utf8mb4';
                $username = 'root';
                $password = 123456;
                $pdo = new PDO($dsn, $username, $password);

// 构建查询字段是否存在的SQL语句
                $sql = "SHOW COLUMNS FROM `$tableName` LIKE '$fieldName'";

// 执行查询
                $stmt = $pdo->query($sql);

// 检查是否有结果返回
                if ($stmt->rowCount() === 0) {
                    // 字段不存在，添加新字段
                    if ($fieldName) {
                        // 注意：这里需要根据你使用的数据库（如MySQL、PostgreSQL等）编写正确的ALTER TABLE语句
                        $alterTableSql = "ALTER TABLE `$tableName` ADD `$fieldName` VARCHAR(50)";
                        $pdo->exec($alterTableSql);
                    }

                }

// 关闭查询语句
                $stmt->closeCursor();


//                if (fieldsExist($table, $fields)) {
//                    echo "字段存在。";
//                } else {
//                Db::table($column, function ($table) use ($column) {
//                    $table->addColumn('varchar', $column, ['length' => 50]); // 示例为varchar类型，长度255
//                });
//                }


            }

        }


        return IndexController::successed('', '成功');


    }


    function fieldsExist($table, array $fields)
    {
        $connection = Db::getConnection();
        $database = $connection->getDatabase();
        $fields = array_map(function ($field) {
            return "'$field'";
        }, $fields);
        $fields = implode(',', $fields);
        $sql = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME IN ($fields)";
        $foundFields = Db::query($sql, [$database, $table])->get()->all();
        return count($foundFields) === count($fields);
    }


    // 更新raw_data到对应字段 同步dcd车型数据
    public function scdRawDataProperties(Request $request)
    {
        $where = [];
        $where [] = ['id', '=', 1];
//        $where [] = ['car_id', '=', 5563];
//        $where [] = ['id', '>', 1];
//        $where [] = ['id', '<=', 2];
//        $where [] = ['id', '<', 34000];
        $rawData = DcdSpecsCansRawData::allByField(['*'], $where);
        $rawData = json_decode($rawData);
        return IndexController::successed(json_encode($rawData), '成功');
        $cans = [
            'official_price
', 'sub_brand_name',
            'sub_brand_id',
            'jb',
            'market_time',
            'length_width_height',
            'car_body_struct',
            'max_speed',
            'acceleration_time',
            'length',
            'width',
            'height',
            'front_track',
            'rear_track',
            'body_struct',
            'door_nums',
            'door_open_way',
            'seat_count',
            'curb_weight',
            'full_load_weight',
            'driver_form',
            'front_suspension_form',
            'rear_suspension_form',
            'power_steering_type',
            'car_body_structure',
            'front_brake_type',
            'rear_brake_type',
            'park_brake_type',
            'front_tire_size',
            'rear_tire_size',
            'abs_anti_lock',
            'brake_force',
            'brake_assist',
            'traction_control',
            'body_stability_system',
            'active_brake',
            'line_support',
            'lane_keeping_assist',
            'lane_center',
            'fatigue_driving_warning',
            'active_dms_fatigue_detection',
            'vital_signs_detection',
            'road_traffic_sign_recognition',
            'signal_recognition',
            'night_vision_system',
            'side_air_curtain',
            'seat_belt_prompted',
            'tire_pressure_system',
            'child_seat_interface',
            'passive_pedestrian_protection',
            'explosion_tire',
            'forward_car_departure_reminder',
            'auto_road_change',
            'auto_road_out_in',
            'auto_park_entry',
            'track_reverse',
            'memory_parking',
            'auto_park',
            'uphill_support',
            'steep_slope',
            'air_suspension',
            'electromagnetic_induct_suspension',
            'variable_steer_system',
            'central_differential_lock',
            'overall_turn',
            'roof_racks',
            'sports_appearance_kit',
            'electric_spoiler',
            'active_closed_inlet_grid',
            'alloy_wheel',
            'frameless_design_door',
            'hidden_door_handle',
            'drag_hook',
            'elec_steer_wheel_adjustment',
            'engine_remote_start',
            'remote_control_move',
            'car_call',
            'header_display_system',
            'built_in_tachograph',
            'active_noise_reduction',
            'mobile_wireless_charging',
            'power_outlet',
            'baggage_12v_power_outlet',
            'sport_style_seat',
            'co_pilot_rear_adjustable_button',
            'rear_cup_holder',
            'hot_cold_cup_holder',
            'navigation_system',
            'position_service',
            'bluetooth_and_car_phone',
            'facial_recognition',
            'fingerprint_recognition',
            'voiceprint_recognition',
            'emotion_recognition',
            'speech_recognition_system',
            'voice_wake_up_free',
            'voice_recognition',
            'visible_to_say',
            'voice_wake_up_word',
            'gesture_control_system',
            'wifi',
            'multi_finger_screen_control',
            'app_store',
            'car_tv',
            'rear_lcd_screen',
            'voice_simulate',
            'rear_touch_control_system',
            'adaptive_light',
            'steer_assist_light',
            'front_fog_light',
            'headlamp_follow_up',
            'headlight_height_adjustment',
            'headlight_clean_function',
            'headlamp_rain_fog_mode',
            'rain_induction_wiper',
            'rear_wiper',
            'heated_nozzle',
            'rear_independent_air_conditioning',
            'rear_exhaust',
            'car_purifier',
            'pm25_filtrating_equipment',
            'hepa_filter_device',
            'negative_ion_generator',
            'car_fragrance_device',
            'heat_pump_management_system',
            'outer_camera_pixel',
            'inner_camera_pixel',
            'high_precision_position_system',
            'sentinel_mode',
            'v2x_communication',
            'car_id',
            'car_year',
            'car_name',
            'series_type',
            'series_name',
            'series_id',
            'product_id',
            'product_series_id',
            'brand_id',
            'brand_name',
            'lane_keeping_a',
            'fuel_form',
            'gps',
            'ar_reality_navigation',
            'car_networking',
            'ota_upgrade',
            'match_value',
            'dealer_text',
            'results_data',
            'is_nev',
            'results_data_all',
            'main_drive_backrest_adjustment',
            'back_armrest',
            'vibrate_feedback',
            'millimeter_wave_radar_3',
            'gearbox_type',
            'compression_ratio_s',
            'vice_drive_backrest_adjustment',
            'second_independent_seat',
            'keyless_entry',
            'max_power_revolution',
            'cylinder_nums,
high_precision_map',
            'mobile_remote_control_6',
            'electric_door',
            'wltc_fuel_comprehensive',
            'multifunction_steer_wheel',
            'rear_usb_typec_interface_count',
            'rear_slip_method',
            'mobile_system_1',
            'main_drive_seat_adjustment',
            'front_windshield_electric_heating',
            'steer_wheel_material_2',
            'cruise',
            'low_headlamp_type',
            'data_network_1',
            'remote_key_3',
            'wheelbase',
            'automatic_drive_level',
            'car_intelligent_system_MOS智慧车联',
            'vice_airbag',
            'high_headlamp_type',
            'engine_anti_theft',
            'lcd_dashboard_size_10.2',
            'engine_max_torque',
            'variable_suspension',
            'air_control_model',
            'engine_model',
            'gearbox_description',
            'light_sensing_canopy',
            'air_supply',
            'reversing_warning_system',
            'second_seat_control_functional',
            'vice_drive_seat_adjustment',
            'mobile_remote_control_5',
            'main_drive_back_and_forth_adjustment',
            'multilayer_soundproof_glass',
            'front_near_center_airbag',
            'second_row_seat_down_ratio',
            'main_drive_window_sunshade_mirror',
            'engine_max_torque_revolution',
            'rear_electric_window',
            'front_armrest',
            'period',
            'stalls',
            'headlamp_delay_off',
            'window_anti_clip_function',
            'keyless_start',
            'voice_wake_up_recognition',
            'cylinder_material',
            'capacity_l',
            'front_collision_warning',
            'lcd_dashboard_type',
            'daytime_light',
            'cylinder_arrangement',
            'full_speed_adaptive_cruise',
            'energy_elect_max_torque',
            'spare_tire_specification_2',
            'auto_headlamp',
            'window_one_key_lift',
            'main_airbag',
            'multimedia_interface_1',
            'main_drive_pillow_adjustment',
            'car_refrigerator',
            'active_ambient_light',
            'front_parking_radar',
            'central_locking_car',
            'oil_supply',
            'mobile_system_2',
            'front_airbag',
            'mobile_remote_control_8',
            'electric_back_door_memory',
            'vice_drive_height_adjustment',
            'vice_drive_waist_adjustment',
            'front_seat_memory',
            'front_seat_ventilation',
            'driving_computer_display_screen',
            'light_special_function',
            'outside_mirror_memory',
            'front_seat_heating',
            'environmental_standards',
            'steer_wheel_adjustment',
            'oil_tank_volume',
            'front_electric_window',
            'vice_drive_back_and_forth_adjustment',
            'valves_per_cylinder_nums',
            'adaptive_cruise',
            'user_custom_pkg',
            'electric_back_door',
            'temperature_partition_control_2',
            'external_mirror_heat',
            'rear_seat_functional',
            'sound_brand',
            'engine_layout_form',
            'external_mirror_auto_flip',
            'base_info',
            'electric_descriptio',
            'wltc_recharge_mileage',
            'cltc_recharge_mileage',
            'high_voltage_fast_charging_platform',
            'battery_charge_time',
            'fast_charge_electricity',
            'energy_elect_max_power',
            'power_consumption',
            'e_energy_equivalent_fuel_consumption',
            'car_body',
            'front_baggage_volume',
            'baggage_volume',
            'min_turning_radius',
            'drag_coefficient',
            'electric_motor',
            'electric_type',
            'total_electric_power',
            'front_electric_max_horsepower',
            'total_electric_torque',
            'rear_electric_max_power',
            'rear_electric_max_torque',
            'electric_drive_number',
            'electric_layout',
            'battery_type',
            'battery_special_technology',
            'battery_brand',
            'battery_warranty',
            'battery_capacity',
            'battery_energy_density',
            'battery_charging_rate',
            'quick_charge_position_v5',
            'slow_charge_position_v5',
            'battery_temperature_management_system',
            'single_footboard_mode',
            'vtol_power_station',
            'max_external_discharge_power',
            'vtov_max_external_discharge_power',
            'gearbox',
            'spare_tire_specification',
            'car_warning_system',
            'main_vice_airbag',
            'front_rear_airbag',
            'main_vice_knee_airbag',
            'parking_radar',
            'driving_assistant_camera',
            'cruise_system',
            'navigation_assisted_driving',
            'automated_valet_parking',
            'front_slip_method',

        ];

        if ($rawData) {
            foreach ($rawData as $krw) {
//                $properties = $krw->properties;
//                $car_info = $krw->car_info;
                $data = [];
                $data['updated_at'] = dateTime();
                $condition = [];
                $condition [] = ['id', '=', $krw->id];
                if ($krw->results_data_all) {

                    foreach ($krw->results_data_all as $ke) {
                        if (in_array($ke->key, $cans)) {
                            if ($ke->key != 'results_data_all') {
                                $data[$ke->key] = $ke->text;
                            }
                        }
                    }
                    $up = DcdSpecsCansRawData::updated($condition, $data);
                    if (!$up) {
                        return IndexController::errored('', '失败');
                    }

                } else {
                    echo '....';
                }
            }
        }
        return IndexController::successed(111, '成功');

    }


    // 懂车帝同步车系照片到车型列表
    public function seriesUrlToSpecs(Request $request)
    {
        $where_specs = [];
//        $where_specs [] = ['id', '=', 1];
//        $where_specs [] = ['car_id', '=', 5563];
        $where_specs [] = ['up_status', '=', 1];
//        $where_specs [] = ['id', '<=', 2];
//        $where_specs [] = ['id', '<', 34000];
        $specs_cans_en_data = DcdSpecsCansEn::all(['id', 'series_id', 'car_id'], $where_specs);
        $specs_cans_en_data = json_decode($specs_cans_en_data);

        if ($specs_cans_en_data) {
            foreach ($specs_cans_en_data as $ksd) {
//                $properties = $krw->properties;
//                $car_info = $krw->car_info;
                $data = [];
                $data['updated_at'] = dateTime();
                $condition = [];
                $condition [] = ['id', '=', $ksd->id];
                $where_series = [];
                $where_series [] = ['series_id', '=', $ksd->series_id];
                $series_data = DcdSeries::find($where_series);
                if ($series_data) {
                    $series_data = json_decode($series_data);
                    $data['cover_url'] = $series_data->cover_url;
                }
                $data ['up_status'] = 2;
                $up = DcdSpecsCansEn::updated($condition, $data);
                if (!$up) {
                    return IndexController::errored('', '失败');
                }

            }
        }
        return IndexController::successed(111, '成功');

    }


    /**
     * 车型车系关联表同步
     * 同步 dcd_series 的 car_ids 到 dcd_specs_id_by_series
     */

    public function carIdsByDcdSeries(Request $request)
    {
        $where_series = [];
        $series_data = DcdSeries::all(['id', 'series_id', 'brand_id', 'car_ids', 'offline_car_ids'], $where_series);
        $series_data = json_decode($series_data);
        $car_ids_ary = [];
        if ($series_data) {
            foreach ($series_data as $kse) {
                if ($kse->car_ids) {
                    $car_ids = explode(',', substr($kse->car_ids, 1, -1));
                    if ($car_ids) {
                        foreach ($car_ids as $kca) {
                            if ($kca) {
                                $ca_data = [
                                    'brand_id' => $kse->brand_id,
                                    'series_id' => $kse->series_id,
                                    'model_id' => $kca,
                                ];
                                array_push($car_ids_ary, $ca_data);
                            }

                        }
                    }
                }

                if ($kse->offline_car_ids) {
                    $offline_car_ids = explode(',', substr($kse->offline_car_ids, 1, -1));
                    if ($offline_car_ids) {
                        foreach ($offline_car_ids as $koff) {
                            if ($koff) {
                                $koff_data = [
                                    'brand_id' => $kse->brand_id,
                                    'series_id' => $kse->series_id,
                                    'model_id' => $koff,
                                ];
                                array_push($car_ids_ary, $koff_data);
                            }

                        }
                    }
                }
            }
        }
        if ($car_ids_ary) {
            foreach ($car_ids_ary as $kspi) {
                \support\Db::table('dcd_specs_id_by_series')->insertGetId($kspi);
            }
        }
        return IndexController::successed(111, '成功');

    }








    /**
     * *********************************************************python 接口转发调用****************************************************
     */

    /**
     * wppy单车型数据爬取-本地
     * @param Request $request
     * @return Response
     */
    public function singleSpecsDownByPython(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition_esixt = [];
        $condition_esixt_data [] = ['car_id', '=', intval($param['car_id'])];
        $find_esixt_data = WpSpecsCans::find($condition_esixt_data);
        $find_esixt_data = json_decode($find_esixt_data);
        $param['formal'] = 1;
        if (array_key_exists('formal', $param)) {
            if ($param['formal']) {
                var_dump(101);
                if ($find_esixt_data) {
                    $scriptPath = "D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/官网-车型数据爬取/单车型id数据更新/main.py"; // Python 脚本路径
                } else {
                    $scriptPath = 'D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/官网-车型数据爬取/单车型id数据爬取/main.py'; // Python 脚本路径
                }
            } else {
                var_dump(102);
                if ($find_esixt_data) {
                    $scriptPath = "D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/在售车型数据爬取/单车型id数据更新/main.py"; // Python 脚本路径
                } else {
                    $scriptPath = 'D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/在售车型数据爬取/单车型id数据爬取/main.py'; // Python 脚本路径
                }

            }

        } else {
            var_dump(103);
            if ($find_esixt_data) {
                $scriptPath = "D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/在售车型数据爬取/单车型id数据更新/main.py"; // Python 脚本路径
            } else {
                $scriptPath = 'D:/phpstudy_pro/WWW/dongchedi/pythonProject/WpDongCheDi/车型数据爬取(只返回car_info部分数据值会时空值)/在售车型数据爬取/单车型id数据爬取/main.py'; // Python 脚本路径
            }

        }


        // 构建命令
        $anacondaPath = 'D:\anaconda3\envs\pythonProject\python.exe'; // Anaconda3 的 Python 解释器路径
        $scriptPath = $scriptPath; // Python 脚本路径
        $arg1 = str($param['car_id']); // 第一个参数
        $arg2 = 'value2'; // 第二个参数

// 使用 escapeshellarg() 来确保参数不会被解释为命令的一部分
        $command = escapeshellcmd("$anacondaPath $scriptPath " . escapeshellarg($arg1));
//        $command = escapeshellcmd("$anacondaPath $scriptPath " . escapeshellarg($arg1) . " " . escapeshellarg($arg2));
//        $command = escapeshellcmd("$anacondaPath $scriptPath"); // 构建完整的命令，并使用 escapeshellcmd // 防止注入攻击 来避免命令注入

// 执行命令并获取输出
        $output = exec($command);
//        if ($output) {
//            //更新 results_data 字段  到 对应字段
//            $condition_syn_data = [];
//            $condition_syn_data [] = ['car_id', '=', intval($param['car_id'])];
//            $find_syn_data = WpSpecsCans::find($condition_syn_data);
//            $find_syn_data = json_decode($find_syn_data);
//            $add_data = [];
//
//            if ($find_syn_data) {
//                if ($find_syn_data->results_data) {
//                    $find_syn_data->results_data = json_decode($find_syn_data->results_data);
//                    foreach ($find_syn_data->results_data as $kr) {
//
//                        $ary = ['jb', 'market_time', 'length_width_height', 'body_struct', 'door_nums', 'seat_count', 'driver_form', 'curb_weight', 'cover_url', 'dealer_price'];
//                        if (in_array($kr->key, $ary)) {
//                            if ($kr->key == 'dealer_price'){
//                                if ($kr->value){
//                                   $a =  explode('万', $kr->value);
//                                    $kr->value = $a[0]*10000;
//                                }
//                            }
//                            $add_data[$kr->key] = $kr->value;
//                        }
//                    }
//
//                }
//
//                if ($find_syn_data->car_head_data) {
//                    $find_syn_data->car_head_data = json_decode($find_syn_data->car_head_data);
//                    foreach ($find_syn_data->car_head_data as $key => $kc) {
//                        if ($kc->official_price){
//                            $f =  explode('万', $kc->official_price);
//                            $kc->official_price = $f[0]*10000;
//                        }
//                        $add_data['brand_id'] = $kc->brand_id;
//                        $add_data['brand_name'] = $kc->brand_name;
//                        $add_data['sub_brand_id'] = $kc->sub_brand_id;
//                        $add_data['sub_brand_name'] = $kc->sub_brand_name;
//                        $add_data['series_id'] = $kc->series_id;
//                        $add_data['series_name'] = $kc->series_name;
//                        $add_data['car_id'] = $kc->car_id;
//                        $add_data['car_name'] = $kc->car_name;
//                        $add_data['official_price'] = $kc->official_price;
//                        $add_data['year'] = $kc->year;
//                        $add_data['img_url'] = $kc->img_url;
//                    }
//
//                }
//
//                $add_condition [] = ['car_id', '=', intval($param['car_id'])];
//                $up_dsc = WPSpecsCans::updated($add_condition, $add_data);
//            }
//        }


        return IndexController::successed($output, '更新完成');
    }

    /**
     * wppy单车型数据爬取接口php-python(flask)
     * @param Request $request
     * @return bool|Response
     */
    public function singleSpec(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 初始化 cURL 会话
        $ch = curl_init();
        // Python接口的URL
        $url = "http://pyu.olivenev.com:5000/main";
        IndexController::logError('python_url', $param, $adminId, $url);
        // 验证 car_id 是否存在
        if (!isset($param['car_id'])) {
            // 处理错误，比如记录日志或返回一个错误响应
            error_log('Missing car_id in request parameters.');
            return json(['code' => 400, 'status' => 'error', 'message' => 'Missing car_id.']);
        }

        $postData = [
            'car_id' => $param['car_id']
        ];

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1); // 设置为 POST 请求

        // 根据服务器端的要求选择正确的数据格式
        // 如果服务器端期望 JSON 格式，则使用以下代码：
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));// 设置 POST 字段
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        // 如果服务器端期望 URL 编码的查询字符串，则使用以下代码（默认情况）：
//        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置 POST 字段

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据而不是直接输出

        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
            // 记录错误日志或执行其他错误处理逻辑
            error_log('cURL Error: ' . curl_error($ch));
            IndexController::logError('cURL Error', $param, $adminId, curl_error($ch));
            return false; // 或者返回一个错误码/异常
        }

        // 关闭 cURL 会话
        curl_close($ch);

        // 处理响应数据（这里假设响应是 JSON 格式）
        $decodedResponse = json_decode($response, true);
        var_dump($decodedResponse);
        if (json_last_error() !== JSON_ERROR_NONE) {
            // 记录 JSON 解码错误日志或执行其他错误处理逻辑
            error_log('JSON Decode Error: ' . json_last_error_msg());
            IndexController::logError('JSON Decode Error', $param, $adminId, json_last_error_msg());
            return false; // 或者返回一个错误码/异常

        }

        // 返回解码后的响应数据
        return json([
            'code' => 200,
            'status' => 'success',
            'output' => $decodedResponse,
        ]);
    }

    /**
     * 懂车帝单车型数据爬取-线上
     * @param Request $request
     * @return Response
     */
    public function singleSpecsDownByPythonOnline(Request $request)
    {
//        $param = $request->all();
////        $adminId = json_decode(adminId($request));
////        var_dump(121111);
////
////
////// 检查 $param 中是否存在 'formal' 键
////        $param['formal'] = isset($param['formal']) ? $param['formal'] : null;
////        $param['formal'] = $param['formal'] ?? 1; // 如果没有提供 'formal'，则默认为 1
////
////// 构建查询条件（这里我们假设 WpSpecsCans::find 方法接受一个数组作为条件）
////        $condition_esixt_data = [['car_id', '=', intval($param['car_id'])]];
////
////// 假设 WpSpecsCans 是一个Eloquent模型或类似的ORM类，但这里我们模拟一个查询结果
////// $find_esixt_data = WpSpecsCans::find($condition_esixt_data); // 这行代码在实际环境中应该有效
////        $find_esixt_data = /* 模拟查询结果 */
////            true; // 我们假设查询成功并返回了数据
////
////// 根据条件选择Python脚本路径（但这次我们将使用远程URL）
////        $remoteScriptBaseUrl = "https://39.103.136.217:31514/www/wwwroot/WpDongCheDi/online/";
////
////        $scriptPath = '';
////
////        if ($param['formal']) {
////            if ($find_esixt_data) {
////                $scriptPath = $remoteScriptBaseUrl . 'upCarHeadDataMain.py';
////            } else {
////                $scriptPath = $remoteScriptBaseUrl . 'getNewDataMain.py';
////            }
////        } else {
////            if ($find_esixt_data) {
////                $scriptPath = $remoteScriptBaseUrl . 'someOtherUpdateScript.py'; // 假设的更新脚本路径
////            } else {
////                $scriptPath = $remoteScriptBaseUrl . 'someOtherCrawlScript.py'; // 假设的爬取脚本路径
////            }
////        }
////
////// 使用 cURL 发送HTTP POST请求到远程Python脚本（假设脚本接受POST数据）
////        $postData = ['car_id' => $param['car_id'], 'formal' => $param['formal']]; // 根据需要调整POST数据
////        $ch = curl_init($scriptPath);
////        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
////        curl_setopt($ch, CURLOPT_POST, true);
////        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 将POST数据编码为查询字符串
////        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
////
////        $response = curl_exec($ch);
////
////        if (curl_errno($ch)) {
////            echo 'Error:' . curl_error($ch);
////        } else {
////            // 处理Python脚本的响应
////            echo $response;
////        }
////
////        curl_close($ch);
////
////
////        return IndexController::successed($response, '更新完成');


        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 初始化 cURL 会话
        $ch = curl_init();
        // Python接口的URL
        $url = "http://pyu.olivenev.com:5000/main";
        IndexController::logError('python_url', $param, $adminId, $url);
        // 验证 car_id 是否存在
        if (!isset($param['car_id'])) {
            // 处理错误，比如记录日志或返回一个错误响应
            error_log('Missing car_id in request parameters.');
            return json(['code' => 400, 'status' => 'error', 'message' => 'Missing car_id.']);
        }

        $postData = [
            'car_id' => $param['car_id']
        ];

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1); // 设置为 POST 请求

        // 根据服务器端的要求选择正确的数据格式
        // 如果服务器端期望 JSON 格式，则使用以下代码：
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));// 设置 POST 字段
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        // 如果服务器端期望 URL 编码的查询字符串，则使用以下代码（默认情况）：
//        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置 POST 字段

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据而不是直接输出

        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
            // 记录错误日志或执行其他错误处理逻辑
            error_log('cURL Error: ' . curl_error($ch));
            IndexController::logError('cURL Error', $param, $adminId, curl_error($ch));
            return false; // 或者返回一个错误码/异常
        }

        // 关闭 cURL 会话
        curl_close($ch);

        // 处理响应数据（这里假设响应是 JSON 格式）
        $decodedResponse = json_decode($response, true);
        var_dump($decodedResponse);
        if (json_last_error() !== JSON_ERROR_NONE) {
            // 记录 JSON 解码错误日志或执行其他错误处理逻辑
            error_log('JSON Decode Error: ' . json_last_error_msg());
            IndexController::logError('JSON Decode Error', $param, $adminId, json_last_error_msg());
            return false; // 或者返回一个错误码/异常

        }

        // 返回解码后的响应数据
        return json([
            'code' => 200,
            'status' => 'success',
            'output' => $decodedResponse,
        ]);
    }


    /**
     * wppy单车型数据更新
     * @param Request $request
     * @return Response
     */
    public function singleSpecsEditByPython(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];
        $car_id = $param['car_id'];
        if ($param['exw_price']) {
            $exw_price = round($param['exw_price'], 2);
        } else {
            $exw_price = 0;

        }
        $car_condition = [];
        $car_condition [] = ['car_id', '=', $param['car_id']];
        $car_find = WpSpecsCans::find($car_condition);
        $car_find = json_decode($car_find);
        if (!$car_find) {
            return IndexController::successed('', '获取车型数据失败');
        }

        $data = [
            'brand_name_en' => $param['brand_name_en'], // 车品牌英文名称
            'car_name_en' => $param['car_name_en'],// 车型英文名称
            'series_name_en' => $param['series_name_en'], // 车系英文名称
            'fuel_form_en' => $param['fuel_form_en'], // 能源英文类型
            'sub_brand_name_en' => $param['sub_brand_name_en'], // 厂商英文名称
            'exw_price' => $exw_price, //
//            'updated_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'admin_name' => $adminId->nickname, // 创建人
        ];
        if ($param['brand_name_en']) {
            // 同步英文字母字段
            if (IndexController::isEnglish($param['car_name_en'])) {
//                $firstLetter = IndexController::firstLetter($param['car_name_en']);
                $dcd_condition = [];
                $dcd_condition [] = ['brand_id', '=', $car_find->brand_id];
                $dcd_data = DcdBrands::find($dcd_condition);
                $dcd_data = json_decode($dcd_data);
                if ($dcd_data) {
                    $data['first_letter'] = $dcd_data->pinyin;
                }
            }
            // 同步品牌表英文字母字段
            $condition_by_brand = [];
            $condition_by_brand [] = ['brand_id', '=', $car_find->brand_id];
            $data_by_brand = [
                'brand_name_en' => $param['brand_name_en'],
            ];
            WpPythonBrands::updated($condition_by_brand, $data_by_brand);
        }

        if (array_key_exists('recommended_model', $param)) {
            if ($param['recommended_model']) {
                $data['recommended_model'] = $param['recommended_model'];
            }
        }


        // 同步车系表英文字母字段
        if ($param['series_name_en']) {

            // 同步品牌表英文字母字段
            $condition_by_series = [];
            $condition_by_series [] = ['series_id', '=', $car_find->series_id];
            $data_by_series = [
                'outter_name' => $param['series_name_en'],
            ];
            WpPythonSeries::updated($condition_by_series, $data_by_series);

        }

        if (array_key_exists('show_status', $param)) {
            $data['show_status'] = $param['show_status'];
        }

        // 先更新本地的数据源
        $condition = [];
        $condition [] = ['car_id', '=', $car_id];
        $up_local_wp = WpSpecsCans::updated($condition, $data);


        // 再更新远程的数据源
        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";
            // 构建 SQL 更新语句的基础部分
            $sql = "UPDATE wp_python_specs_cans SET ";
            foreach ($data as $key => $value) {
                $setClauses[] = "`$key` = :$key";
                // 直接在这里绑定参数
            }
            $sql .= implode(', ', $setClauses);
            // 添加 WHERE 子句
            $sql .= " WHERE car_id = :car_id";

            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);

            // 动态构建 SET 子句和参数数组
            $setClauses = [];
            $params = [];
            foreach ($data as $key => $value) {
                $stmt->bindValue(":$key", $value);
            }

            // 再次绑定 car_id 参数（如果它在 $data 中已经存在，则不需要再次绑定）
            $stmt->bindValue(':car_id', $car_id);

            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }
            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json($result_data), '更新成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '更新失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '更新完成');
    }


    /**
     * 懂车帝品牌数据列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function brandListAllByDcdBrands(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%'];
        }

        $fields = ["*"];
        $listOrder = DcdBrands::all($fields, $condition);

        return IndexController::successed($listOrder, '懂车帝品牌列表');
    }

    /**
     * 懂车帝车系数据列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function seriesListAllByDcdSeries(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        $whereIn = [];
        if (array_key_exists('brand_id', $param)) {
            if ($param['brand_id']) {
                $condition [] = ['brand_id', '=', $param['brand_id']];
            }
        }

        if ($param['series_name']) {
            $condition [] = ['outter_name', 'like', '%' . $param['series_name'] . '%'];
        }


        $fields = ["*"];
        $listOrder = DcdSeries::all($fields, $condition);

        return IndexController::successed($listOrder, '懂车帝车系列表');
    }

    /**
     * 车帝wp数据列表
     * @param Request $request
     * @return Response
     */
    public function singleSpecsListByPython(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        $whereIn = [];
        if ($param['car_name']) {
            $condition [] = ['car_name', 'like', '%' . $param['car_name'] . '%'];
        }

        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%'];
        }

        if ($param['series_name']) {
            $condition [] = ['series_name', 'like', '%' . $param['series_name'] . '%'];
        }

        if (array_key_exists('brand_id', $param)) {
            if ($param['brand_id']) {
                $whereIn = $param['brand_id'];
            }
        }

        if (array_key_exists('series_id', $param)) {
            if ($param['series_id']) {
                $whereIn = $param['series_id'];
            }
        }

        $pageNum = $param['pageNum'];

        $fields = ["brand_id",
            "brand_name", "brand_name_en", "car_id", "car_name", "car_name_en", "car_year", "series_name",
            "series_name_en", "series_id", "fuel_form", "fuel_form_en", "is_nev", "official_price", "sub_brand_name",
            "sub_brand_name_en", "sub_brand_id", "jb", "market_time", "length_width_height", "body_struct",
            "door_nums", "seat_count", "driver_form", "curb_weight", "img_url", 'dealer_price', 'exw_price', 'recommended_model'];
        $page = $param['page'];
        $listOrder = WpSpecsCans::list($page, $pageNum, $fields, $condition, $whereIn);

        return IndexController::successed($listOrder, 'Wp车型列表');
    }

    /**
     * wppy单车型数据删除
     * @param Request $request
     * @return Response
     */
    public function singleSpecsDel(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];
        $car_id = $param['car_id'];

        // 先删除本地的数据源
        $condition = [];
        $condition [] = ['car_id', '=', $car_id];
        $del_wp = WpSpecsCans::deleted($condition);

        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        // 再删除远程的数据源
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";
            // 构建 SQL 更新语句的基础部分
            $sql = "DELETE FROM wp_python_specs_cans";

            // 添加 WHERE 子句
            $sql .= " WHERE car_id = :car_id";

            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);

            // 再次绑定 car_id 参数（如果它在 $data 中已经存在，则不需要再次绑定）
            $stmt->bindValue(':car_id', $car_id);

            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }
            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json_encode($result_data), '删除成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '删除失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '删除完成');
    }

    /**
     * wppy品牌数据列表 - 分页
     * @param Request $request
     * @return Response
     */
    public function brandPageListByPyBrands(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%'];
        }
        if ($param['brand_name_en']) {
            $condition [] = ['brand_name_en', 'like', '%' . $param['brand_name_en'] . '%'];
        }

        $pageNum = $param['pageNum'];

        $fields = ["*"];
        $page = $param['page'];
        $listOrder = WpPythonBrands::list($page, $pageNum, $fields, $condition);

        return IndexController::successed($listOrder, 'Wp车型列表');
    }

    /**
     * wppy品牌数据列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function brandAllListByPyBrands(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        if ($param['brand_name']) {
            $condition [] = ['brand_name', 'like', '%' . $param['brand_name'] . '%'];
        }
        if ($param['brand_name_en']) {
            $condition [] = ['brand_name_en', 'like', '%' . $param['brand_name_en'] . '%'];
        }


        $fields = ["*"];
        $listOrder = WpPythonBrands::all($fields, $condition);

        return IndexController::successed($listOrder, 'Wp车型列表');
    }

    /**
     * wppy车系数据列表 - 分页
     * @param Request $request
     * @return Response
     */
    public function seriesPageListByPySeries(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        $whereIn = [];
        if (array_key_exists('brand_id', $param)) {
            if ($param['brand_id']) {
                $whereIn = $param['brand_id'];
            }
        }

        if ($param['series_name']) {
            $condition [] = ['outter_name', 'like', '%' . $param['series_name'] . '%'];
        }

        if ($param['series_name_en']) {
            $condition [] = ['outter_name_en', 'like', '%' . $param['series_name_en'] . '%'];
        }

        $pageNum = $param['pageNum'];

        $fields = ["*"];
        $page = $param['page'];
        $listOrder = WpPythonSeries::list($page, $pageNum, $fields, $condition, $whereIn);

        return IndexController::successed($listOrder, 'Wp车型列表');
    }

    /**
     * wppy车系数据列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function seriesAllListByPySeries(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        if (array_key_exists('brand_id', $param)) {
            if ($param['brand_id']) {
                $condition [] = ['brand_id', '=', $param['brand_id']];
            }
        }

        if ($param['series_name']) {
            $condition [] = ['outter_name', 'like', '%' . $param['series_name'] . '%'];
        }

        if ($param['series_name_en']) {
            $condition [] = ['outter_name_en', 'like', '%' . $param['series_name_en'] . '%'];
        }

        $fields = ["*"];
        $listOrder = WpPythonSeries::all($fields, $condition);

        return IndexController::successed($listOrder, 'Wp车型列表');
    }

    /**
     * wppy品牌添加 - 从已知表里选择 dcd-brands
     * @param Request $request
     * @return Response
     */
    public function brandAddByDcdBrands(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];

        if ($param['brand_id']) {
            $condition_by_dcdbra = [];
            $condition_by_dcdbra [] = ['brand_id', '=', $param['brand_id']];
            $DcdBrandsData = DcdBrands::find($condition_by_dcdbra);
            $DcdBrandsData = json_decode($DcdBrandsData);
            if ($DcdBrandsData) {
                $param['brand_id'] = $DcdBrandsData->brand_id; //
                $param['brand_name'] = $DcdBrandsData->brand_name; //
                $param['image_url'] = $DcdBrandsData->image_url; //
                $param['pinyin'] = $DcdBrandsData->pinyin; //
                $param['first_letter'] = $DcdBrandsData->pinyin; //
            }

        }

        $data = [
            'brand_id' => $param['brand_id'], //
            'brand_name' => $param['brand_name'],//
            'image_url' => $param['image_url'], //
            'pinyin' => $param['pinyin'], //
            'first_letter' => $param['pinyin'], //
        ];


        // 先更新本地的数据源 但是要先查询是否已存在
        $condition_by_pb = [];
        $condition_by_pb [] = ['brand_id', '=', $param['brand_id']];
        $find_local_wp = WpPythonBrands::find($condition_by_pb);
        $find_local_wp = json_decode($find_local_wp);
        if ($find_local_wp) {
            return IndexController::errored('', '该品牌已存在');
        }


        $add_local_wp = WpPythonBrands::created($data);
        if (!$add_local_wp) {
            return IndexController::errored('', '添加失败');
        }


        // 再更新远程的数据源
        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";
            // 构建 SQL 更新语句的基础部分
            $sql = "INSERT INTO wp_python_brands (brand_id, brand_name, image_url, pinyin, first_letter) 
            VALUES (:brand_id, :brand_name, :image_url, :pinyin, :first_letter)";
            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);
            // 绑定参数并执行 SQL 语句
            $stmt->bindParam(':brand_id', $param['brand_id']);
            $stmt->bindParam(':brand_name', $param['brand_name']);
            $stmt->bindParam(':image_url', $param['image_url']);
            $stmt->bindParam(':pinyin', $param['pinyin']);
            $stmt->bindParam(':first_letter', $param['pinyin']);
            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }
            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json($result_data), '更新成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '更新失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '更新完成');
    }

    /**
     * wppy品牌编辑
     * @param Request $request
     * @return Response
     */
    public function brandEditByWppy(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];


        $condition = [];
        $condition [] = ['brand_id', '=', $param['brand_id']];
        $data = [];
        $data['brand_name_en'] = $param['brand_name_en'];//
        $DcdBrandsData = DcdBrands::find($condition);
        $DcdBrandsData = json_decode($DcdBrandsData);
        if ($DcdBrandsData) {
            $data['pinyin'] = $DcdBrandsData->pinyin; //
            $data['first_letter'] = $DcdBrandsData->pinyin; //
        }


        $up_local_wp = WpPythonBrands::updated($condition, $data);


        // 再更新远程的数据源
        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";

            // 构建 SQL 更新语句的基础部分
            $sql = "UPDATE wp_python_brands SET ";

            // 动态构建 SET 子句和参数数组
            foreach ($data as $key => $value) {
                $setClauses[] = "`{$key}` = :{$key}";
                $params[":{$key}"] = $value;
            }

            $sql .= implode(', ', $setClauses);

            // 添加 WHERE 子句
            $sql .= " WHERE brand_id = :brand_id";

            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);

            // 动态构建 SET 子句和参数数组
            $setClauses = [];
            $params = [];
            $stmt->bindValue(":brand_name_en", $param['brand_name_en']);
            $stmt->bindValue(":pinyin", $DcdBrandsData->pinyin);
            $stmt->bindValue(":first_letter", $DcdBrandsData->pinyin);
            // 再次绑定 car_id 参数（如果它在 $data 中已经存在，则不需要再次绑定）
            $stmt->bindValue(':brand_id', $param['brand_id']);

            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }

            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json($result_data), '更新成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '更新失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '更新完成');
    }


    /**
     * wppy车系编辑
     * @param Request $request
     * @return Response
     */
    public function seriesEditByWppy(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];

        $condition = [];
        $condition [] = ['series_id', '=', $param['series_id']];
        $data = [
            'outter_name_en' => $param['series_name_en'],//
//            'image_url' => $param['image_url'], //
        ];
        $up_local_wp = WpPythonSeries::updated($condition, $data);


        // 再更新远程的数据源
        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";

            // 构建 SQL 更新语句的基础部分
            $sql = "UPDATE wp_python_series SET ";

            // 动态构建 SET 子句和参数数组
            foreach ($data as $key => $value) {
                $setClauses[] = "`{$key}` = :{$key}";
                $params[":{$key}"] = $value;
            }

            $sql .= implode(', ', $setClauses);
            // 添加 WHERE 子句
            $sql .= " WHERE series_id = :series_id";

            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);

            // 动态构建 SET 子句和参数数组
            $setClauses = [];
            $params = [];
            $stmt->bindValue(":outter_name_en", $param['series_name_en']);

            // 再次绑定 car_id 参数（如果它在 $data 中已经存在，则不需要再次绑定）
            $stmt->bindValue(':series_id', $param['series_id']);

            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }

            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json($result_data), '更新成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '更新失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '更新完成');
    }


    /**
     * // wppy车系添加 - 从已知表里选择 dcd-series
     * @param Request $request
     * @return Response
     */
    public function seriesAddByDcdSeries(Request $request)
    {

        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];

        if ($param['series_id']) {
            $condition_by_dcdbra = [];
            $condition_by_dcdbra [] = ['series_id', '=', $param['series_id']];
            $DcdBrandsData = DcdSeries::find($condition_by_dcdbra);
            $DcdBrandsData = json_decode($DcdBrandsData);
            if ($DcdBrandsData) {
                $param['brand_id'] = $DcdBrandsData->brand_id; //
                $param['brand_name'] = $DcdBrandsData->brand_name; //
                $param['cover_url'] = $DcdBrandsData->cover_url; //
                $param['series_id'] = $DcdBrandsData->series_id; //
                $param['outter_name'] = $DcdBrandsData->outter_name; //
                $param['car_ids'] = $DcdBrandsData->car_ids; //
                $param['offline_car_ids'] = $DcdBrandsData->offline_car_ids; //
                $param['image_url'] = $DcdBrandsData->image_url; //
            }

        }

        $data = [
            'brand_id' => $param['brand_id'], //
            'brand_name' => $param['brand_name'],//
            'cover_url' => $param['cover_url'], //
            'series_id' => $param['series_id'], //
            'outter_name' => $param['outter_name'], //
            'car_ids' => $param['car_ids'], //
            'offline_car_ids' => $param['offline_car_ids'], //
            'image_url' => $param['image_url'], //
        ];


        // 先更新本地的数据源 但是要先查询是否已存在
        $condition_by_pb = [];
        $condition_by_pb [] = ['series_id', '=', $param['series_id']];
        $find_local_wp = WpPythonSeries::find($condition_by_pb);
        $find_local_wp = json_decode($find_local_wp);
        if ($find_local_wp) {
            return IndexController::errored('', '该品牌已存在');
        }


        $add_local_wp = WpPythonSeries::created($data);
        if (!$add_local_wp) {
            return IndexController::errored('', '添加失败');
        }


        // 再更新远程的数据源
        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";
            // 构建 SQL 更新语句的基础部分
            $sql = "INSERT INTO wp_python_series (brand_id, brand_name, cover_url, series_id, outter_name, car_ids,offline_car_ids, image_url) 
            VALUES (:brand_id, :brand_name, :cover_url, :series_id, :outter_name, :car_ids, :offline_car_ids,  :image_url)";
            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);
            // 绑定参数并执行 SQL 语句
            $stmt->bindParam(':brand_id', $param['brand_id']);
            $stmt->bindParam(':brand_name', $param['brand_name']);
            $stmt->bindParam(':cover_url', $param['cover_url']);
            $stmt->bindParam(':series_id', $param['series_id']);
            $stmt->bindParam(':outter_name', $param['outter_name']);
            $stmt->bindParam(':car_ids', $param['car_ids']);
            $stmt->bindParam(':offline_car_ids', $param['offline_car_ids']);
            $stmt->bindParam(':image_url', $param['image_url']);
            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }
            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json($result_data), '更新成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '更新失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '更新完成');
    }

    /**
     * wppy品牌数据删除
     * @param Request $request
     * @return Response
     */
    public function brandDeleteByBrandId(Request $request)
    {

        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息
        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress;charset=utf8mb4;auth=mysql_native_password';

//        $dsn = 'mysql:host=54.255.95.66;port=3306;dbname=wordpress';
        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];
        $brand_id = $param['brand_id'];

        // 先删除本地的数据源
        $condition = [];
        $condition [] = ['brand_id', '=', $brand_id];
        $del_wp = WpPythonBrands::deleted($condition);

        \support\Db::beginTransaction();
        echo "Before connection attempt...";
        // 再删除远程的数据源
        try {
            // 创建 PDO 实例，建立数据库连接
            $pdo = new PDO($dsn, $username, $password, $options);
            echo "Connection successful!";
            // 构建 SQL 更新语句的基础部分
            $sql = "DELETE FROM wp_python_brands";

            // 添加 WHERE 子句
            $sql .= " WHERE brand_id = :brand_id";

            // 预处理 SQL 语句
            $stmt = $pdo->prepare($sql);

            // 再次绑定 car_id 参数（如果它在 $data 中已经存在，则不需要再次绑定）
            $stmt->bindValue(':brand_id', $brand_id);

            // 执行 SQL 语句
            if ($stmt->execute()) {
                $result_data = ['status' => 'success', 'message' => 'Record updated successfully'];
            } else {
                $result_data = ['status' => 'error', 'message' => 'Failed to update record'];
            }
            \support\Db::commit();
            // 返回成功响应
            return IndexController::successed(json_encode($result_data), '删除成功');

        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            // 捕获 PDO 异常，记录错误日志，并返回错误响应
            error_log($e->getMessage());
            $result_data = ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
            return IndexController::successed(json_encode($result_data), '删除失败');

        }
        echo "After connection attempt...";
        return IndexController::successed('', '删除完成');
    }

    /**
     * 二手车同步新车车型数据
     * @param Request $request
     * @return Response
     */
    public function dcdUsedModelUpByNew(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 数据库连接配置信息

        $username = 'wordpress';
        $password = 123456;
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];


        $used_car_fields = ['*'];
        $used_car_condition = [];
        $used_car_all = WpUsedSpecsCans::all($used_car_fields,$used_car_condition);
        $used_car_all = json_decode($used_car_all);
        if ($used_car_all) {
            foreach ($used_car_all as $kused) {
                $condition_km = [];
                $condition_km [] = ['id', '=', $kused->id];
//                $data_km = [
//                    'mileage' => round($kused->mileage,2) * 10000,
//                ];
//                $up_local_wp_used = WpUsedSpecsCans::updated($condition_km, $data_km);
                $car_condition = [];
                $car_condition [] = ['brand_id', '=', $kused->brand_id];
//            $car_find = WpSpecsCans::find($car_condition);
                $brand_find = DcdBrands::find($car_condition);
                $brand_find = json_decode($brand_find);
                if ($brand_find) {
                    $data = [
//                        'brand_name_en' => $brand_find->brand_name_en, // 车品牌英文名称
//                        'car_name_en' => $car_find->car_name_en,// 车型英文名称
//                        'series_name_en' => $car_find->series_name_en, // 车系英文名称
//                        'fuel_form_en' => $car_find->fuel_form_en, // 能源英文类型
//                        'sub_brand_name_en' => $car_find->sub_brand_name_en, // 厂商英文名称
                        'first_letter' => $brand_find->pinyin, // 厂商英文名称
                    ];
                    // 先更新本地的数据源
                    $condition = [];
                    $condition [] = ['brand_id', '=', $kused->brand_id];
                    $up_local_wp_used = WpUsedSpecsCans::updated($condition, $data);
                }
            }

        }else{
            return IndexController::successed('', '获取二手车车型数据失败');

        }
        return IndexController::successed('', '更新完成');

    }





}